package com.swallow.cloud.common.config;

import com.swallow.cloud.common.security.shiro.SystemAuthRealm;
import com.swallow.cloud.common.utils.Global;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 权限配置
 * @Author: L.swallow
 * @Date: 2019/5/6 17:29
 */

@Configuration
public class ShiroConfig {


    /**
     * 基础权限配置
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        bean.setLoginUrl(Global.getConfig("shiro.loginUrl"));
        bean.setSuccessUrl(Global.getConfig("adminPath")+"/index");
        // 拦截规则
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put(Global.getConfig("shiro.loginUrl"), "authc");
        filterChainDefinitionMap.put(Global.getConfig("adminPath"), "user");
        filterChainDefinitionMap.put("/**", "authc");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }

    /**
     * 注入 securityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(systemAuthRealm());
        return securityManager;
    }

    /**
     * 认证Realm
     * @return
     */
    @Bean
    public SystemAuthRealm systemAuthRealm() {
        return new SystemAuthRealm();
    }
}
